#!/usr/bin/perl
# 2011/12/26 Bed fileで指定された部位のenrichmentをすべて出力する

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;


if(@ARGV != 4 or $ARGV[0] eq '--help'){
	die "Usage : $0 -w [wig file] -b [bed file]\n";
}

my %opt;
getopts("b:w:", \%opt);

my $FILE_bed = $opt{b};
my $FILE_wig = $opt{w};


#---------------------------------------
# read wig file
#---------------------------------------
my %WIG;
#track type=wiggle_0 name=pKu70
#variableStep chrom=chr1 span=30
#50      33.541859
#80      29.758246
#110     26.788264
#140     24.255730
#170     21.654645
#200     19.378484
{
	my $fh = IO::File->new($FILE_wig) or die "cannot open $FILE_wig: $!";
	$fh->getline();
	my $chr = '';
	while($_ = $fh->getline()){
		s/\r?\n//;
		if(m/^#/){
			next;
		}
		if(m/chrom=(\w+)/){
			$chr = $1;
		}else{
			my ($pos, $value) = split /\t/;
			if($value < 0){
				$value = 0;
			}
			$WIG{$chr}{$pos} = $value;
		}
	}
	$fh->close();
}


#---------------------------------------
# read bed file
#---------------------------------------
#chr1    1568383 1568732 LTR.31  0       -       1568383 1568732 0       1       349,    0,
#chr1    2173898 2174235 LTR.35  0       -       2173898 2174235 0       1       337,    0,
#chr1    2474234 2474583 LTR.39  0       -       2474234 2474583 0       1       349,    0,
#chr1    2693885 2694225 LTR.41  0       -       2693885 2694225 0       1       340,    0,
#chr1    2843758 2844091 LTR.42  0       -       2843758 2844091 0       1       333,    0,
{
	my $fh = IO::File->new($FILE_bed) or die "cannot open $FILE_bed: $!";
	while($_ = $fh->getline()){
		s/\r?\n//;
		if(m/^#/){
			next;
		}
		my ($chr, $start, $end, $t1, $t2, $direction, @other) = split /\t/;
		my $calc_start = $start - 2000;
		my $calc_end = $end + 2000;

		my $MAX = 0;
		for(my $i = $calc_start; $i <= $calc_end; $i++){
			my $score = $WIG{$chr}{$i} ? $WIG{$chr}{$i} : 0;
			if($score > $MAX){
				$MAX = $score;
			}
		}
		print "$_\t$MAX\n";
	}
	$fh->close();
}

